package vn.game;

import java.util.ArrayList;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import vn.game.R;
public class CreateGame extends Activity implements OnClickListener {
	/** Called when the activity is first created. */
	public String tag = "CreateGame";
//	private static final int SELECT_PHOTO = 100;

	EditText edit;
//	EditText edtName;
//	Spinner spnKind;
	GridView gridView;
	Button btnAddRow;
	Button btnSave;
//	Button btnBackground;
	Button btnCancel;
	TextViewAdapter textAdapter;
	LinearLayout lnMainLayout;
	LinearLayout lnAcross;
	LinearLayout lnDown;

	// Gird
	int row, column;
	LinearLayout lnGridItem;
	LinearLayout lnGrid;

	int countNum = 0;
	int countID = 0;
	CrossWordDbAdapter mDbHelper;
	ArrayList<clsWordDetail> arrList;
	ListView lv1;
	// ArrayList<clsData> myArray = new ArrayList<clsData>();

	ImageView view2;

	// Dialog
	public EditText tvDialog;
	Dialog dialog;
	int countR = 0;
	int countC = 0;
	EditText edtRow;
	EditText edtCol;

	int gameId = -1;

	int widthWindow;
	int widthCell = 33;

	// sd card path
	String pathImg = "";

	// ///////////////////////

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.create);
		try {
			initCtrl();

//			Intent intent = getIntent();
//			if (intent != null)
//				gameId = intent.getIntExtra("idGame", 0);
			// gameId = 1;

			Display display = getWindowManager().getDefaultDisplay();
			widthWindow = display.getWidth();

			mDbHelper = new CrossWordDbAdapter(this);
			mDbHelper.open();

//			String arrKind[] = { "All", "Other", "History", "Literary", "Geographical", "Music", "Sport" };
//			ArrayAdapter<String> adapter;
//			adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrKind);
//			spnKind.setAdapter(adapter);

//			if (gameId > 0) {
//				btnSave.setText("Update");
//				btnAddRow.setEnabled(false);
////				LoadGame(gameId);
//				LoadHint(gameId);
//			} else {
//				btnSave.setText("Save");
//				btnAddRow.setEnabled(true);
				// Set Row and column for grid
				setRowCol();
//			}

			lnGrid.setLayoutParams(new LinearLayout.LayoutParams(widthCell * column, widthCell * row + 20));

			gridView.setNumColumns(column);
			textAdapter = new TextViewAdapter(this, row * column);
			textAdapter.setCount(row * column);
			gridView.setAdapter(textAdapter);

		} catch (Exception ex) {
			Log.e(tag ,"OnCreate:" + ex.getMessage());
		}
	}

	private void initCtrl() {
		countID = 0;
		arrList = new ArrayList<clsWordDetail>();

//		edtName = (EditText) findViewById(R.id.edtNameGame);
//		spnKind = (Spinner) findViewById(R.id.spnKind);

		btnAddRow = (Button) findViewById(R.id.btnAddRow);
		btnAddRow.setOnClickListener(this);

		btnSave = (Button) findViewById(R.id.btnSave);
		btnSave.setOnClickListener(this);

//		btnBackground = (Button) findViewById(R.id.btnBackground);
//		btnBackground.setOnClickListener(this);

		btnCancel = (Button) findViewById(R.id.btnCancel);
		btnCancel.setOnClickListener(this);

		lnMainLayout = (LinearLayout) findViewById(R.id.MainLayout);
		lnAcross = (LinearLayout) findViewById(R.id.lnAcross);
		lnDown = (LinearLayout) findViewById(R.id.lnDown);

		lnGrid = (LinearLayout) findViewById(R.id.lnGrid);
		gridView = (GridView) findViewById(R.id.grid);

	}

	public void onClick(View v) {
		// TODO Click
		Log.i(tag + "Click", "called");
		switch (v.getId()) {
		case R.id.btnAddRow:
			setClickListener();
			break;
		case R.id.btnSave:
			try {
				if (checkValue()) {
					// set number for display
					setNum();
//					if (gameId > 0)
//						updateGame();
//					else
						SaveGame();
					// clear data of grid
					clearGrid();

					clearAll();
				}
			} catch (Exception ex) {
				Log.i(tag + "setOnClickListener", ex.getMessage());
			}
			break;
//		case R.id.btnBackground:
//			getBackground();
//			break;
		case R.id.btnCancel:
			finish();
			break;

		}
	}

//	private void LoadGame(int id) {
//		// TODO Load game
//		String kind;
//		try {
//			Cursor cur = mDbHelper.getGame(id);
//			startManagingCursor(cur);
//
//			if (cur != null) {
//				while (cur.moveToNext()) {
//					row = cur.getInt(0);
//					column = cur.getInt(1);
//					edtName.setText(cur.getString(2));
//					kind = cur.getString(3);
//					for (int i = 0; i < spnKind.getCount(); i++) {
//						if (kind.equals(spnKind.getItemAtPosition(i).toString())) {
//							spnKind.setSelection(i);
//							break;
//						}
//					}
//
//				}
//			}
//
//			if (cur != null && !cur.isClosed()) {
//				cur.close();
//			}
//
//		} catch (Exception ex) {
//			Log.i(tag + "LoadGame", ex.getMessage());
//		}
//	}

//	private void LoadHint(int id) {
//		// TODO load hint
//		try {
//			Cursor cur = mDbHelper.GetDetail(id);
//			startManagingCursor(cur);
//
//			if (cur != null) {
//				while (cur.moveToNext()) {
//					// addHint(boolean across, int pos, String words, String hint)
//					addHint(cur.getInt(1), cur.getInt(2) == 1, cur.getInt(3), cur.getString(4), cur.getString(5));
//				}
//			}
//
//			if (cur != null && !cur.isClosed()) {
//				cur.close();
//			}
//
//		} catch (Exception ex) {
//			Log.i(tag + "LoadHint", ex.getMessage());
//		}
//	}

	// Set row and column for grid
	private void setRowCol() {
		column = widthWindow / widthCell - 1;
		row = column;
	}

	// Set action for Dialog Form
	private void setClickListener() {
		// TODO set action for dialog
		dialog = new Dialog(CreateGame.this);
		dialog.setContentView(R.layout.number_picker);
		dialog.setTitle("Add row and column");

		edtRow = (EditText) dialog.findViewById(R.id.edtRow);
		edtCol = (EditText) dialog.findViewById(R.id.edtCol);

		edtRow.setText(row + "");
		edtCol.setText(column + "");

		// Increment row of grid
		Button btnIncrementR = (Button) dialog.findViewById(R.id.btnIncrementR);
		btnIncrementR.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Increment row on grid
				int count;
				try {
					count = Integer.parseInt(edtRow.getText().toString()) + 1;
					edtRow.setText(count + "");
				} catch (Exception ex) {
					edtRow.setText("1");
				}
			}
		});

		// Decrement row of grid
		Button btnDecrementR = (Button) dialog.findViewById(R.id.btnDecrementR);
		btnDecrementR.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Decrement row on grid
				int count;
				try {
					count = Integer.parseInt(edtRow.getText().toString());
					if (count > 1)
						count--;
					edtRow.setText(count + "");
				} catch (Exception ex) {
					edtRow.setText("1");
				}

			}
		});

		// Increment column of grid
		Button btnIncrementC = (Button) dialog.findViewById(R.id.btnIncrementC);
		btnIncrementC.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Increment col on grid
				int count;
				try {
					count = Integer.parseInt(edtCol.getText().toString()) + 1;
					edtCol.setText(count + "");
				} catch (Exception ex) {
					edtRow.setText("1");
				}
			}
		});

		// Decrement column of grid
		Button btnDecrementC = (Button) dialog.findViewById(R.id.btnDecrementC);
		btnDecrementC.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Decrement col on grid
				int count;
				try {

					count = Integer.parseInt(edtCol.getText().toString());
					if (count > 1)
						count--;
					edtCol.setText(count + "");
				} catch (Exception ex) {
					edtRow.setText("1");
				}
			}
		});

		// Add row and column of grid
		Button btnAdd_dialog = (Button) dialog.findViewById(R.id.btnAdd);
		btnAdd_dialog.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO add row and column on grid
				try {
					reSetRow(Integer.parseInt(edtRow.getText().toString()), Integer.parseInt(edtCol.getText().toString()));
				} catch (Exception ex) {
					reSetRow(14, 14);
				}
				dialog.dismiss();

			}
		});

		// Cancel
		Button btnCancel = (Button) dialog.findViewById(R.id.btnCancel);
		btnCancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO cancel dialog
				dialog.dismiss();

			}
		});
		// Show dialog
		dialog.show();

	}

	// Check input value
	private boolean checkValue() {
		// TODO check value of edit
//		if (edtName.getText().toString().trim().equals("")) {
//			Toast.makeText(this, "Enter Name", Toast.LENGTH_SHORT).show();
//			return false;
//		}
		if (arrList.size() < 1) {
			Toast.makeText(this, "Enter word on grid", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

//	// update to DB
//	private void updateGame() {
//		try {
//			clsWord data = new clsWord();
//			data.setName(edtName.getText().toString());
////			data.setKind(spnKind.getSelectedItem().toString());
//			data.setRow(row);
//			data.setColumn(column);
//			data.setId(gameId);
//			data.setPathImg(pathImg);
//
//			if (mDbHelper.updateGame(data)) {
//				mDbHelper.deleteAdetail(gameId);
//				mDbHelper.insertDetail(gameId, arrList);
//				Log.i(tag + "updateGame", "Update successful");
//				edtName.setText("");
//				countNum = 0;
//				Toast.makeText(this, "update successful", Toast.LENGTH_SHORT).show();
//			}
//
//		} catch (Exception ex) {
//			Log.i(tag + ".insertGame", ex.getMessage());
//		}
//	}

	// save to DB
	private void SaveGame() {
		// TODO Save data to database
		long id;
		try {
			clsWord data = new clsWord();
//			data.setName(edtName.getText().toString());
//			data.setKind(spnKind.getSelectedItem().toString());
			data.setRow(row);
			data.setColumn(column);
			data.setPlayed(0);
//			data.setPathImg(pathImg);
			id = mDbHelper.insertGame(data);
			if (id > 0) {
				id = mDbHelper.insertDetail(id, arrList);
				Log.i(tag, "SaveGame() Insert successfull id:" + id);
//				edtName.setText("");
				countNum = 0;
				Toast.makeText(this, "Saved successful", Toast.LENGTH_SHORT).show();
			}
			

		} catch (Exception ex) {
			Log.i(tag, "SaveGame() Error: " + ex.getMessage());			
		}

	}

	private void setNum() {
		int i = 1;
		boolean check = false;
		for (clsWordDetail data : arrList) {
			if (data.isAcross())
				data.setNum(i++);
		}
		for (clsWordDetail data : arrList) {
			if (data.isAcross() == false) {
				for (clsWordDetail data2 : arrList) {
					if (data.getPos() == data2.getPos() && data2.isAcross() == true) {
						data.setNum(data2.getNum());
						check = true;
						break;
					}
				}
				if (!check)
					data.setNum(i++);
				check = false;
			}
		}
	}

	public class TextViewAdapter extends BaseAdapter {
		// TODO class TextViewAdapter
		Context MyContext;
		private int count;

		public TextViewAdapter(Context _MyContext, int count) {
			MyContext = _MyContext;
			this.count = count;
		}

		public void setCount(int count) {
			this.count = count;
		}

		public int getCount() {
			return count;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			// View MyView = convertView;
			ExtTextView tv = null;

			try {
				if (convertView == null) {
					countID++;
					tv = new ExtTextView(MyContext);
					tv.setId(countID);
					tv.setLayoutParams(new GridView.LayoutParams(widthCell, widthCell));
					tv.setOnClickListener(new OnClickListener() {
						public void onClick(View v) {
							// TODO Auto-generated method stub
							Intent intent = new Intent(v.getContext(), InputWords.class);
							intent.putExtra("location", v.getId());
							startActivityForResult(intent, 1);
						}
					});
				} else {
					tv = (ExtTextView) convertView;
				}

				if (countID >= row * column) {
					loadGird();
				}
			} catch (Exception ex) {
				Log.i(tag + "onActivityResult", "Error: " + ex.getMessage());
			}
			return tv;
		}

		public Object getItem(int arg0) {
			return null;
		}

		public long getItemId(int arg0) {
			return 0;
		}
	}

	public void reSetRow(int row, int column) {
		this.row = row;
		this.column = column;

		// set width for cell on grid
		if (46 < widthWindow / column) {
			widthCell = 43;
		} else {
			widthCell = 33;
		}

		clearAll();

		lnGrid.setLayoutParams(new LinearLayout.LayoutParams(widthCell * column, widthCell * row + 15));
		countID = 0;
		textAdapter = new TextViewAdapter(this, row * column);
		gridView.setNumColumns(column);
		textAdapter.setCount(row * column);
		gridView.setAdapter(textAdapter);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		boolean across;
		int pos;
		String word;
		try {
			if (resultCode == RESULT_OK) {
				if (data.hasExtra("words")) {
					Log.i(tag,"onResult...");
					across = data.getExtras().getBoolean("orientation");
					pos = data.getExtras().getInt("postion");
					word = data.getExtras().getString("words");
					word = getFixWord(across, word, pos);
					addHint(0, across, pos, word, data.getExtras().getString("hint"));
					loadGird();
				} 
//				else if (requestCode == SELECT_PHOTO) {
//					Uri selectedImage = data.getData();
//					if (selectedImage != null) {
//						String[] filePathColumn = { MediaStore.Images.Media.DATA };
//						Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
//						cursor.moveToFirst();
//
//						int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
//						pathImg = cursor.getString(columnIndex);
//						cursor.close();
//
//						Bitmap bitmap = BitmapFactory.decodeFile(pathImg);
//						BitmapDrawable background = new BitmapDrawable(bitmap);
//
//						lnMainLayout.setBackgroundDrawable(background);
//					}
//				}
			}
		} catch (Exception ex) {
			Log.i("CreateGame.onActivityResult", "Error: " + ex.getMessage());
		}
	}
//
//	private void getBackground() {
//		Intent intent = new Intent(Intent.ACTION_PICK, (MediaStore.Images.Media.EXTERNAL_CONTENT_URI));
//		startActivityForResult(intent, SELECT_PHOTO);
//	}

	private void addHint(int num, boolean across, int pos, String words, String hint) {
		int id;

		TextView txtNum = new TextView(this);
		TextView txtHint = new TextView(this);
		LinearLayout ln = new LinearLayout(this);

		extButton btnSub = new extButton(this);
		try {
			id = ++countNum;
			ln.setOrientation(0);

			if (num > 0)
				txtNum.setText(num + "");
			else
				txtNum.setText(id + "");
			txtNum.setId(1000 + id);
			txtNum.setWidth(25);
			txtNum.setTextColor(Color.BLUE);

			txtHint.setText(hint);
			txtHint.setId(2000 + id);
			txtHint.setWidth(380);
			if (hint.length() > 65)
				txtHint.setHeight(100);

			btnSub.setText("-");
			btnSub.setId(3000 + id);
			btnSub.setWidth(50);
			btnSub.setHeight(5);
			btnSub.setPosWord(across, pos, words);
			btnSub.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub
					int id;
					try {
						id = v.getId();
						extButton btnT = (extButton) findViewById(id);
						LinearLayout lnTemp = (LinearLayout) v.getParent();
						((LinearLayout) lnTemp.getParent()).removeView(lnTemp);
						for (clsWordDetail wd : arrList) {
							if (wd.getPos() == btnT.getPos() && wd.getWords() == btnT.getWords()) {
								arrList.remove(wd);
								break;
							}
						}
						loadGird();

					} catch (Exception ex) {
						Log.i(tag + "onClick", "Error:" + ex.getMessage());
					}
				}
			});

			ln.addView(txtNum);
			ln.addView(txtHint);
			ln.addView(btnSub);
			if (across)
				lnAcross.addView(ln);
			else
				lnDown.addView(ln);

			clsWordDetail wd = new clsWordDetail();
			if (num > 0)
				wd.setNum(num);
			else
				wd.setNum(countNum);
			wd.setAcross(across);
			wd.setPos(pos);
			wd.setWords(words);
			wd.setHint(hint);
			arrList.add(wd);
		} catch (Exception ex) {
			Log.i(tag + "addHint", "Error:" + ex.getMessage());
		}

	}

	public void clearGrid() {
		int count = 1;
		int numRow = 1;
		try {
			for (int i = 0; i < column; i++)
				for (int j = 0; j < row; j++) {
					ExtTextView tv = (ExtTextView) findViewById(count);
					if (tv != null) {
						tv.setBackgroundColor(Color.DKGRAY);
						tv.onDrawBackground(true);
						tv.setText("");
						if (count <= column)
							tv.onDrawText(count + "", true);
						if ((count - 1) % column == 0)
							tv.onDrawText((numRow++) + "", true);
					}
					count++;
				}
		} catch (Exception ex) {
			Log.i(tag + ".clearGrid", count + ", Error:" + ex.getMessage());
		}
	}

	public void clearAll() {
		// clear data of ListView
		lnAcross.removeAllViews();
		// clear data of ListView
		lnDown.removeAllViews();

		arrList.removeAll(arrList);
	}

	public void loadGird() {
		int id;
		try {
			clearGrid();
			if (arrList == null && arrList.size() <= 0)
				return;
			for (clsWordDetail wd : arrList) {
				char[] chWords = wd.getWords().toCharArray();
				if (wd.isAcross()) {
					for (int i = 0; i < chWords.length; i++) {
						ExtTextView tv = (ExtTextView) findViewById(wd.getPos() + i);
						tv.onDrawBackground(false);
						tv.setBackgroundColor(Color.WHITE);
						tv.setTextColor(Color.BLACK);
						tv.setText(chWords[i] + "");
						if (i == 0)
							tv.onDrawText(wd.getNum() + "");
					}

				} else {
					for (int i = 0; i < chWords.length; i++) {
						id = wd.getPos() + column * i;
						if (id <= row * column) {
							ExtTextView tv = (ExtTextView) findViewById(id);
							tv.onDrawBackground(false);
							tv.setBackgroundColor(Color.WHITE);
							tv.setTextColor(Color.BLACK);
							tv.setText(chWords[i] + "");
							if (i == 0)
								tv.onDrawText(wd.getNum() + "");
						}
					}
				}
			}
		} catch (Exception ex) {
			Log.i(tag + "loadGird", "Error:" + ex.getMessage());
		}

	}

	private String getFixWord(boolean across, String word, int pos) {
		int temp = 0;
		int colW, rowW;
		char[] chWords = word.toCharArray();
		String strWord = "";
		if (across) {
			colW = pos % column;
			if (colW == 0)
				return chWords[0] + "";
			for (int i = colW; i <= column; i++) {
				if (temp < chWords.length)
					strWord += chWords[temp++] + "";
				else
					break;
			}
		} else {
			temp = 0;
			rowW = pos / column;
			for (int i = rowW; i <= row; i++) {
				if (temp < chWords.length)
					strWord += chWords[temp++] + "";
				else
					break;
			}
		}

		return strWord;
	}

	public class extButton extends Button {
		int pos;
		boolean across;
		String words;

		public extButton(Context context) {
			super(context);
			// TODO Auto-generated constructor stub
		}

		public void setPosWord(boolean across, int pos, String words) {
			this.pos = pos;
			this.across = across;
			this.words = words;
		}

		public int getPos() {
			return pos;
		}

		public void setPos(int pos) {
			this.pos = pos;
		}

		public boolean isAcross() {
			return across;
		}

		public void setAcross(boolean across) {
			this.across = across;
		}

		public String getWords() {
			return words;
		}

		public void setWords(String words) {
			this.words = words;
		}
	}

	public void onDestroy() {
		super.onDestroy();
		try {
			if (mDbHelper != null){
				mDbHelper.close();
				mDbHelper=null;
			}
		} catch (Exception ex) {
			Log.i(tag, "***** onDestroy() Error: " + ex.getMessage());
		}
	}
	
	/* Initiating Menu XML file (menu.xml) */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.layout.menu_playgame, menu);
		return true;
	}



}
